package com.example.baselibrary.base

import android.app.Application
import android.os.Build
import android.os.Process
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import androidx.multidex.MultiDex
import cat.ereza.customactivityoncrash.config.CaocConfig
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.example.baselibrary.BuildConfig
import com.example.baselibrary.Constant
import com.example.baselibrary.app.event.AppViewModel
import com.example.baselibrary.app.event.EventViewModel
import com.example.baselibrary.app.weight.loadCallBack.EmptyCallback
import com.example.baselibrary.app.weight.loadCallBack.ErrorCallback
import com.example.baselibrary.app.weight.loadCallBack.LoadingCallback
import com.example.baselibrary.ui.ErrorActivity
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.LoadSir
import com.tencent.bugly.Bugly
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import me.hgj.jetpackmvvm.ext.util.jetpackMvvmLog
import me.hgj.jetpackmvvm.ext.util.logd

//Application全局的ViewModel，里面存放了一些账户信息，基本配置信息等
val appViewModel: AppViewModel by lazy { BaseModuleInit.appViewModelInstance }

//Application全局的ViewModel，用于发送全局通知操作
val eventViewModel: EventViewModel by lazy { BaseModuleInit.eventViewModelInstance }

class BaseModuleInit : IModuleInit , ViewModelStoreOwner {

    private  var mAppViewModelStore: ViewModelStore = ViewModelStore()
    companion object {
        lateinit var eventViewModelInstance: EventViewModel
        lateinit var appViewModelInstance: AppViewModel
    }

    override fun onInitAhead(application: Application): Boolean {
        initMMKV(application)
        LogUtils.e("基础业务模块初始化 -- onInitAhead")
        eventViewModelInstance =
            getAppViewModelProvider(application).get(EventViewModel::class.java)
        appViewModelInstance =
            getAppViewModelProvider(application).get(AppViewModel::class.java)
        initMultiDex(application)

        //初始化阿里路由框架
        if (BuildConfig.DEBUG) {
            ARouter.openLog() // 打印日志
            ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(application) // 尽可能早，推荐在Application中初始化
      return false
    }

    override fun onInitLow(application: Application): Boolean {
        LogUtils.e("基础业务模块初始化 -- onInitLow")
        initBugly(application)
        initCaocConfig()
        initLoadSir()
        return false
    }

    /**
     * 界面加载管理 初始化
     */
    fun initLoadSir(){
        LoadSir.beginBuilder()
            .addCallback(LoadingCallback())//加载
            .addCallback(ErrorCallback())//错误
            .addCallback(EmptyCallback())//空
            .setDefaultCallback(SuccessCallback::class.java)//设置默认加载状态页
            .commit()
    }

    fun initBugly(application: Application){
        //初始化Bugly
        val context = application.applicationContext
        // 获取当前包名
        val packageName = context.packageName
        // 获取当前进程名
        val processName = com.example.baselibrary.app.ext.getProcessName(Process.myPid())
        // 设置是否为上报进程
        val strategy = CrashReport.UserStrategy(context)
        strategy.isUploadProcess = processName == null || processName == packageName
        // 初始化Bugly
        Bugly.init(context, if (Constant.DEBUG) "xxx" else "a52f2b5ebb", Constant.DEBUG)
        "".logd()
        jetpackMvvmLog = com.zhpan.indicator.BuildConfig.DEBUG
    }

    /**
     * 存储初始化
     */
    fun initMMKV(application: Application){

        MMKV.initialize(application.filesDir.absolutePath + "/mmkv")
    }

    /**
     * 分包
     */
    fun initMultiDex(application: Application){
        MultiDex.install(application)
    }


    /**
     * 防止项目崩溃，崩溃后打开错误界面
     */
    fun initCaocConfig(){
        //防止项目崩溃，崩溃后打开错误界面
        CaocConfig.Builder.create()
            .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
            .enabled(true)//是否启用CustomActivityOnCrash崩溃拦截机制 必须启用！不然集成这个库干啥？？？
            .showErrorDetails(false) //是否必须显示包含错误详细信息的按钮 default: true
            .showRestartButton(false) //是否必须显示“重新启动应用程序”按钮或“关闭应用程序”按钮default: true
            .logErrorOnRestart(false) //是否必须重新堆栈堆栈跟踪 default: true
            .trackActivities(true) //是否必须跟踪用户访问的活动及其生命周期调用 default: false
            .minTimeBetweenCrashesMs(2000) //应用程序崩溃之间必须经过的时间 default: 3000
//            .restartActivity(WelcomeActivity::class.java) // 重启的activity
            .errorActivity(ErrorActivity::class.java) //发生错误跳转的activity
            .apply()
    }

    /**
     * 初始化工具类
     */
    fun initUtils(){



    }


    //----------------在Activity/fragment中获取Application级别的ViewModel-------------------


    private var mFactory: ViewModelProvider.Factory? = null

    override fun getViewModelStore(): ViewModelStore {
        return mAppViewModelStore
    }



    /**
     * 获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(application: Application): ViewModelProvider {
        return ViewModelProvider(this, getAppFactory(application))
    }

    private fun getAppFactory(application: Application): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        }
        return mFactory as ViewModelProvider.Factory
    }


}